package wzq.cn.wuziqi.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

import wzq.cn.wuziqi.utils.LogUtils;

/**
 * Created by xiawei on 15/8/23.
 */
public class RecylerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {


    private SparseArray<View> views;
    private View convertView;
    private BaseRecylerViewAdapter.RecylerViewItemClickListener itemClickListener;

    public RecylerViewHolder(View convertView) {
        super(convertView);
        this.views = new SparseArray<View>();
        this.convertView = convertView;
        this.convertView.setOnClickListener(this);
        convertView.setTag(this);
    }

    public BaseRecylerViewAdapter.RecylerViewItemClickListener getItemClickListener() {
        return itemClickListener;
    }

    public void setItemClickListener(BaseRecylerViewAdapter.RecylerViewItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public static RecylerViewHolder get(View convertView) {
        RecylerViewHolder existedHolder = (RecylerViewHolder) convertView.getTag();
        if (existedHolder == null) {
            return new RecylerViewHolder(convertView);
        }
        return existedHolder;
    }

    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = convertView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public <T extends View> T getView(int viewId, InitViewListener listener) {
        View view = views.get(viewId);
        if (view == null) {
            view = convertView.findViewById(viewId);
            if (listener != null) {
                listener.initView(view);
            }
            views.put(viewId, view);
        }
        return (T)view;
    }


    public interface InitViewListener {
        public void initView(View view);
    }


    @Override
    public void onClick(View v) {
        if (itemClickListener != null) {
            itemClickListener.onItemClick(v, getPosition());
        }
        LogUtils.d("item","onClick");
    }


    public View getConvertView() {
        return convertView;
    }

    public void setConvertView(View convertView) {
        this.convertView = convertView;
    }
}